const axios = require('axios');
const qs = require('qs');

axios.defaults.withCredentials = true
// axios.defaults.crossDomain=true
// 发送时
axios.interceptors.request.use(config => {
  // if (process.env.NODE_ENV === 'gray'&&config.url.startsWith('http://192.168.150.180:20070')) {
  //   config.headers['Host'] = 'restapi.safeappcore.hlwxxaq.glb.cmos';
  // }
  return config
}, err => {
  return Promise.reject(err)
})

function checkStatus(res) {
  if (res.status === 200 || res.status === 304) {
    return res.data
  }
}

// 响应时
axios.interceptors.response.use(response => {
  try {
    if (response.status != 200) {
      console.log('request', response.status, response.request.responseURL);
    }
  } catch (e) {
  }
  return response;
}, err => {
  return Promise.resolve(err.response);
})
module.exports = {
  get(url, params) {
    if (!url) return
    
    let config = {
      method: 'get',
      url: url,
      params,
      timeout: 30000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
      }
    }
    
    // let env = process.env.NODE_ENV;
    // if (env == 'test') {
    //   config.proxy = {
    //     host: '172.22.225.70',
    //     port: 23128,
    //   }
    // }
    return axios(config).then(checkStatus)
  },
  post(url, data, headers) {
    let head = {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    };
    if (headers) {
      Object.assign(head, headers);
    }
    
    let config = {
      method: 'post',
      url: url,
      data: qs.stringify(data),
      timeout: 30000,
      headers: head
    }
    // let env = process.env.NODE_ENV;
    // if (env == 'test') {
    //   config.proxy = {
    //     host: '172.22.225.70',
    //     port: 23128,
    //   }
    // }
    return axios(config).then(checkStatus)
  },
  postBody(url, data, headers, isProxy) {
    let head = {
      'Content-Type': 'application/json;charset=UTF-8'
    };
    
    if (headers) {
      Object.assign(head, headers);
    }
    
    let config = {
      method: 'post',
      url: url,
      data: data,
      timeout: 30000,
      headers: head,
    };
    if (isProxy) {
      config.proxy = {
        host: '172.22.225.70',
        port: 23128,
      }
    }
    return axios(config).then(checkStatus)
  }
}
